#include "dbhelper.h"

DbHelper::DbHelper(const QString &dbname)
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(dbname);
    bool ok = db.open();
    if(ok == false){
        qDebug() << db.lastError();
    }else{
        query = new QSqlQuery(db);
    }
}

bool DbHelper::regist(const QString &name, const QString &pswd)
{
    query->prepare("insert into stu(name,pswd) values(:name,:pswd)");
    query->bindValue(":name",name);
    query->bindValue(":pswd",pswd);
    // ③ 执行数据库语句
    bool ok = query->exec();

    if(ok == false){
        qDebug() << query->lastError();
        //QMessageBox::warning(NULL,"数据库","该账号已存在");
    }else{
        //QMessageBox::information(NULL,"数据库","注册成功");
    }
    return ok;
}

bool DbHelper::login(const QString &name, const QString &pswd)
{
    query->prepare("select pswd from stu where name = :name");
    query->bindValue(":name",name);
    bool ok = query->exec();
    if(ok == false){
        qDebug() << query->lastError();
        return false;
    }

    if(query->next() == false){
        //QMessageBox::warning(NULL,"登录","该账号不存在");
        return false;
    }

    QString db_pswd = query->value("pswd").toString();
    if(db_pswd == pswd){
        //QMessageBox::information(NULL,"登录","登录成功");
        return true;
    }else{
        //QMessageBox::warning(NULL,"登录","密码错误");
        return false;
    }
}

bool DbHelper::createTable(const QString &sql)
{
    bool ok = query->exec(sql);
    if(ok == false){
        qDebug() << query->lastError();
    }
    return ok;
}

int DbHelper::getRow()
{
    bool ok = query->exec("select label from face order by label desc limit 1"); // 查询数据，按照label大小逆序查询，并且只显示label的值，并且只显示一条记录
    if(ok == false){
        qDebug() << query->lastError();
        return -1;
    }
    if(query->next() == false){ // 如果没有查到任何记录，说明没有人脸，行号为0
        return 0;
    }
    return query->value("label").toInt();
}

bool DbHelper::faceRegist(const QString &name, int label)
{
    query->prepare("insert into face(name,label) values(:name,:label)");
    query->bindValue(":name",name);
    query->bindValue(":label",label);
    bool ok = query->exec();
    if(ok == false){
        qDebug() << query->lastError();
    }
    return ok;
}

QString DbHelper::facePredict(int label)
{
    query->prepare("select name from face where label = :label");
    query->bindValue(":label",label);
    bool ok = query->exec();
    if(query->next() == false || ok == false){
        qDebug() << query->lastError();
        return "";
    }

    return query->value("name").toString();
}

void DbHelper::clearTable(const QString &tb)
{
    query->prepare("drop :table");
    query->bindValue(":table",tb);
    bool ok = query->exec();
    if(ok == false){
        qDebug() << query->lastError();
    }
}

void DbHelper::close()
{
    db.close();
}
